<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申报Id" prop="declarationId">
        <el-input
          v-model="queryParams.declarationId"
          placeholder="请输入申报Id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable>
          <el-option
            v-for="dict in dict.type.t_declaration_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人姓名" prop="applicant">
        <el-input
          v-model="queryParams.applicant"
          placeholder="请输入申请人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申报单位" prop="department">
        <el-input
          v-model="queryParams.department"
          placeholder="请输入申报单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申报日期">
        <el-date-picker
          v-model="daterangeApplicationDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="申报审核状态" prop="statu">
        <el-select v-model="queryParams.statu" placeholder="请选择申报审核状态" clearable>
          <el-option
            v-for="dict in dict.type.t_review_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tongyan:declaration:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tongyan:declaration:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tongyan:declaration:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tongyan:declaration:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="declarationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键ID" align="center" prop="declarationId"/>
      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="项目类型" align="center" prop="projectType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.t_declaration_type" :value="scope.row.projectType"/>
        </template>
      </el-table-column>
      <el-table-column label="申请人姓名" align="center" prop="applicant"/>
      <el-table-column label="申报单位" align="center" prop="department"/>
      <el-table-column label="申报日期" align="center" prop="applicationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目简介" align="center" prop="researchContent"/>
      <el-table-column label="项目经费" align="center" prop="budget"/>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申报审核状态" align="center" prop="statu">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.t_review_status" :value="scope.row.statu"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tongyan:declaration:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tongyan:declaration:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改科研项目申报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="form.projectType" placeholder="请选择项目类型">
            <el-option
              v-for="dict in dict.type.t_declaration_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请人姓名" prop="applicant">
          <el-input v-model="form.applicant" placeholder="请输入申请人姓名"/>
        </el-form-item>
        <el-form-item label="申报单位" prop="department">
          <el-input v-model="form.department" placeholder="请输入申报单位"/>
        </el-form-item>
        <el-form-item label="申报日期" prop="applicationDate">
          <el-date-picker clearable
                          v-model="form.applicationDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择申报日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目简介" prop="researchContent">
          <el-input v-model="form.researchContent" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <!--        <el-form-item label="用户id" prop="userId">-->
        <!--          <el-input v-model="form.userId" placeholder="请输入内容"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="项目经费" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入项目经费"/>
        </el-form-item>
        <el-form-item label="预期成果" prop="expectedResults">
          <el-input v-model="form.expectedResults" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="研究团队" prop="researchTeam">
          <el-input v-model="form.researchTeam" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="附件存储路径" prop="filePath">
          <file-upload v-model="form.filePath" :fileType="['pdf', 'doc', 'docx', 'xls', 'xlsx']"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDeclaration,
  getDeclaration,
  delDeclaration,
  addDeclaration,
  updateDeclaration
} from "@/api/tongyan/declaration";
import jwtDecode from 'jwt-decode';

export default {
  name: "Declaration",
  dicts: ['t_declaration_type', 't_review_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研项目申报表格数据
      declarationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 附件存储路径时间范围
      daterangeApplicationDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectType: null,
        applicant: null,
        department: null,
        applicationDate: null,
        statu: null,
        declarationId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        projectType: [
          {required: true, message: "项目类型不能为空", trigger: "change"}
        ],
        applicant: [
          {required: true, message: "申请人姓名不能为空", trigger: "blur"}
        ],
        department: [
          {required: true, message: "申报单位不能为空", trigger: "blur"}
        ],
        applicationDate: [
          {required: true, message: "申报日期不能为空", trigger: "blur"}
        ],
        researchContent: [
          {required: true, message: "项目简介不能为空", trigger: "blur"}
        ],
        budget: [
          {required: true, message: "项目经费不能为空", trigger: "blur"}
        ],
        statu: [
          {required: true, message: "申报审核状态不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
    // const user = JSON.parse(localStorage.getItem('user'));
    // if (user && user.userId) {
    //   this.form.userId = user.userId;
    // }
  },
  methods: {
    /** 查询科研项目申报列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeApplicationDate && '' != this.daterangeApplicationDate) {
        this.queryParams.params["beginApplicationDate"] = this.daterangeApplicationDate[0];
        this.queryParams.params["endApplicationDate"] = this.daterangeApplicationDate[1];
      }
      listDeclaration(this.queryParams).then(response => {
        this.declarationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        declarationId: null,
        projectName: null,
        projectType: null,
        applicant: null,
        department: null,
        applicationDate: null,
        researchContent: null,
        budget: null,
        expectedResults: null,
        researchTeam: null,
        contactInfo: null,
        createdAt: null,
        updatedAt: null,
        filePath: null,
        statu: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
        this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeApplicationDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.declarationId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加科研项目申报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const declarationId = row.declarationId || this.ids
      getDeclaration(declarationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改科研项目申报";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // const user = JSON.parse(localStorage.getItem('user'));
      // if (user && user.userId) {
      //   this.form.userId = user.userId;
      //   this.$modal.msgError('User ID:', user.userId);
      // }
      // const token = localStorage.getItem('username');
      // this.$modal.msgError(token);
      // if (token) {
      //   const decoded = jwtDecode(token);
      //   const userId = decoded.userId;
      //   console.log('User ID:', userId);
      //   this.$modal.msgError('User ID:', userId);
      // }else{
      //   //this.$modal.msgError("请先登录");
      // }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.declarationId != null) {
            updateDeclaration(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeclaration(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const declarationIds = row.declarationId || this.ids;
      this.$modal.confirm('是否确认删除科研项目申报编号为"' + declarationIds + '"的数据项？').then(function () {
        return delDeclaration(declarationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tongyan/declaration/export', {
        ...this.queryParams
      }, `declaration_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
